package com.zpz.framework.zpzoauth.common.encrypt;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class DefaultCrypto {
    private static final Logger logger = LoggerFactory.getLogger(DefaultCrypto.class);
    /*
    * 验证签名
    * @data 加密+压缩+编码之后
    * */
    public static boolean signatureValid(String data,String nonceStr,String signKey,String sign)throws Exception{
        return SignUtil.MD5(data+nonceStr+signKey).toUpperCase().equals(sign.toUpperCase());
    }
    public static boolean signatureValid(Map<String,String> data, String nonceStr, String timestamp, String signKey, String sign)throws Exception{
        String s = RSAUtil.formatSignParam(data);
        logger.info("签名的Base64之前的明文参数：：：：：："+ s);
        s = Base64.encodeBase64String(s.getBytes("UTF-8"));
        logger.info("签名的Base64：：："+ s);
        String str= s+nonceStr+timestamp;
        // MD5withRSA 生成数字签名
        String verifysign = SignUtil.MD5(str + signKey);
        return verifysign.equals(sign);
    }

    /*
     * 私钥解密
     * @data 加密+压缩+编码之后
     * */
    public static String decodDataPrivateKey(String data,String privateKey)throws Exception{
        logger.info(String.format("数据----------%s-------私钥------%s",data,privateKey));
        //base64解码
        byte[] encryptedData = Base64.decodeBase64(data);
        //解压
        //byte[] unzip = ZipUtil.unzip(encryptedData);
        //解密
        byte[] decryptedData = RSAUtil.decryptByPrivateKey(encryptedData, privateKey);
        String result = new String(decryptedData);
        logger.info(String.format("------解密数据------%s",result));
        return result;
    }
    /*
     * 公钥加密
     *
     * */
    public static String encodDataPublicKey(String data,String publicKey)throws Exception{
        //加密
        byte[] bytes = RSAUtil.encryptByPublicKey(data.getBytes("UTF-8"), publicKey);
        //压缩
        //byte[] zip = ZipUtil.zip(bytes);
        //编码
        String re = Base64.encodeBase64String(bytes);
//            String re=new String(bytes);
        return re;
    }
    /*
     * 私钥加密
     *
     * */
    public static String encodDataPrivateKey(String data,String privateKey)throws Exception{
        //加密
        byte[] bytes = RSAUtil.encryptByPrivateKey(data.getBytes(), privateKey);
        //压缩
        byte[] zip = ZipUtil.zip(bytes);
        //编码
        String re = Base64.encodeBase64String(zip);
        return re;
    }
    /*
     * 签名
     * @data 加密+压缩+编码之后
     * */
    public static String sign(String data,String nonceStr,String signKey)throws Exception{
        String sign = SignUtil.MD5(data+nonceStr+signKey);
        return sign;
    }

    public static String sign(Map<String,String> data, String nonceStr,String timestamp, String privateKey)throws Exception{
        String s = RSAUtil.formatSignParam(data);
        logger.info("签名的Base64之前的明文参数：：：：：："+ s);
        s = Base64.encodeBase64String(s.getBytes("UTF-8"));
        logger.info("签名的Base64：：："+ s);
        String str= s+nonceStr+timestamp;
        // MD5withRSA 生成数字签名
        String sign = SignUtil.MD5(str + privateKey);
//        String sign = RSAUtil.sign(str.getBytes(), privateKey);
        return sign;
    }
    public static void main(String[] args) {
        try {
            String s=" additionalInformation={\"author\":\"create by zpz-oauth\",\"jti\":\"f16a72b5-c4d5-4969-993a-f21f2530ef82\",\"license\":\"made by zpz.com\",\"ucode\":\"1131819850441990144\"}&expiration=1591695255043&expired=false&expiresIn=7199&refreshToken={\"expiration\":1594280054980,\"value\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsaWNlbnNlIjoibWFkZSBieSB6aGlzY2l0eS5jb20iLCJ1c2VyX25hbWUiOiIxNTAxMDUyNjY3MCIsImF1dGhvciI6ImNyZWF0ZSBieSB6aGlzY2l0eS1vYXV0aCIsInNjb3BlIjpbImFsbCJdLCJhdGkiOiJmMTZhNzJiNS1jNGQ1LTQ5NjktOTkzYS1mMjFmMjUzMGVmODIiLCJleHAiOjE1OTQyODAwNTQsInVjb2RlIjoiMTEzMTgxOTg1MDQ0MTk5MDE0NCIsImp0aSI6ImQyZmE1YjNjLTA1NDItNGI1Zi05Mjg2LTAyNDUxZjY5ODRjYSIsImNsaWVudF9pZCI6InpjeXlnbF93ZWIiLCJyZWdpc3Rlcl9zdGF0dXMiOm51bGx9.3KLThZF56oiZSY1BhzCESGaaBtFsdZzQUhqq33lUCk0\"}&scope=[\"all\"]&tokenType=bearer&value=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsaWNlbnNlIjoibWFkZSBieSB6aGlzY2l0eS5jb20iLCJ1c2VyX25hbWUiOiIxNTAxMDUyNjY3MCIsImF1dGhvciI6ImNyZWF0ZSBieSB6aGlzY2l0eS1vYXV0aCIsInNjb3BlIjpbImFsbCJdLCJleHAiOjE1OTE2OTUyNTUsInVjb2RlIjoiMTEzMTgxOTg1MDQ0MTk5MDE0NCIsImp0aSI6ImYxNmE3MmI1LWM0ZDUtNDk2OS05OTNhLWYyMWYyNTMwZWY4MiIsImNsaWVudF9pZCI6InpjeXlnbF93ZWIiLCJyZWdpc3Rlcl9zdGF0dXMiOm51bGx9.AyDfs363MCG5_UCwTuAoQWTW0N7Dz0puYtEcamg8v0k";
            String sign = SignUtil.MD5(s+"8T49tEp8GA7nnj2sq0UMvWhyfMefPxjb"+"1591688055383" + "b292c22796c156468e2f839adace8f83");
            System.out.println(sign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // rsa
//        try {
//            String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJCwQaXeySZ/bBCRL36cqbeGP6QxpIA2dzSlr9CMV28mD+JNwAM8YeIJdjE6U0wURaiZnISkcjPoPVR+tWlQCssyvFPqqplFeQ2HXzQG/WYJ1BXw75r/1IwfSdTUGNeLjrI7/Kt8RjabFlX+a5R99cIiTljd1S8EWcxmHg0qWPpXAgMBAAECgYBclEsNJUY0Geg9mYh4TSnTQlVKbHFDkJYp27JpkMMJXaNgPDuWVnaTOValHRrbXUVNIi0iOk7Qo9NKU2Ekp5CfgCT4DkODFcPsewfL/agQBJKUhJ5aKmDkcs2/PTs0xJNMAP7nPsaDFfAKOk0kH5xA7jj1+Otx+LXTEc5juI4VYQJBAP7HjqsjL8u/3ytkzJ/uK0iRc0odxxl2DhBO9tvz7sIjAynCBY7AIqcTJsPr9v0p762tI/e7rANe9RAzjiP9p1kCQQCRYbER/VMfvoPk9OdA18mUZfnFwOy9+RxML5BPVKYsFibSYRUsCegRo29v4gwFOEoYXKkP8hsP4HtZquxhiikvAkEA0aIZPa9CEH/bfLT/uUgazScAmadOvyBoCfsvG2PmvE5at+0w7XgiCx6y8tog68WptFmWEqyUqGFleuMwvWRkYQJAU8v6c0MP+Zknjv32mXKH10icGnckPi/rNqKnzIIfMgQmpladDIA9SoVowxWJFi0m0DoAnJdRL+qVTs7tZx9qswJBAMP35Ag+8UFJBFzLSqb5ipHaWiNpWaYe2oRqrVbtVu7byjaTp9fgscyOByu+JbJeIaeTi2JCJCdpZoqRe1cAItA=";
//            String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQsEGl3skmf2wQkS9+nKm3hj+kMaSANnc0pa/QjFdvJg/iTcADPGHiCXYxOlNMFEWomZyEpHIz6D1UfrVpUArLMrxT6qqZRXkNh180Bv1mCdQV8O+a/9SMH0nU1BjXi46yO/yrfEY2mxZV/muUffXCIk5Y3dUvBFnMZh4NKlj6VwIDAQAB";
//            String signKey = "414c92090b5f05cf372101c3426adfa2";
//            //原始数据体
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("shortMsgCode", "123456");
//            jsonObject.put("phoneNumber", "18311109710");
//            jsonObject.put("password", "123456");
//            String jsonStr = jsonObject.toJSONString();
//           /* //加密
//            byte[] bytes = RSAUtil.encryptByPublicKey(jsonStr.getBytes(), publicKey);
//            //压缩
//            byte[] zip = ZipUtil.zip(bytes);
//            //编码
//            String string = Base64.encodeBase64String(zip);*/
//            String string = encodDataPublicKey(jsonStr, publicKey);
//            System.out.println("加密数据"+string);
//            //签名
//            String nonceStr= SignUtil.generateNonceStr();
//            System.out.println("随机字符串："+nonceStr);
////            String sign = SignUtil.MD5(string+nonceStr+signKey);
//            String sign = sign(string, nonceStr, signKey);
//            System.out.println("签名："+sign);
//            /************************************************/
//            //验签
//            boolean signatureValid = signatureValid(string, nonceStr, signKey, sign);
////            boolean signatureValid = SignUtil.MD5(string+nonceStr+signKey).toUpperCase().equals(sign.toUpperCase());
//            System.out.println("\t\n验证签名："+signatureValid);
//            /*//base64解码
//            byte[] encryptedData = Base64.decodeBase64(string);
//            //解压
//            byte[] unzip = ZipUtil.unzip(encryptedData);
//            //解密
//            byte[] decryptedData = RSAUtil.decryptByPrivateKey(unzip, privateKey);
//            String result = new String(decryptedData, "UTF-8");*/
//            String result = decodDataPrivateKey(string, privateKey);
//            System.out.println("解密数据："+result);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }
}
